package com.home.zzm.myaccountbook

import android.content.Context
import android.content.pm.PackageInfo
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.home.zzm.myaccountbook.databinding.ActivityAccountLoginBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import android.content.pm.PackageManager




class AccountLoginActivity : BaseActivity() {
  private lateinit var binding: ActivityAccountLoginBinding
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityAccountLoginBinding.inflate(layoutInflater)
    setContentView(binding.root)

    initViews()
    initData()
    initEvent()
  }

  private fun initEvent() {
  }

  private fun initData() {
    Log.e("zzm debug","initData")
    CoroutineScope(Dispatchers.Main).launch {
      withContext(Dispatchers.IO){
        if(isAvilible(this@AccountLoginActivity,"com.baidu.BaiduMap")){
          Log.e("zzm debug","installed")
        }else{
          Log.e("zzm debug","not installed")
        }
      }
    }
  }

  private fun initViews() {
    Toast.makeText(this, "欢迎使用XX", Toast.LENGTH_SHORT).show()
  }

  /**
   * 检查手机上是否安装了指定的软件
   * @param context
   * @param packageName：应用包名
   * @return
   */
  private suspend fun isAvilible(context: Context, packageName: String): Boolean {
    //获取packagemanager
    val packageManager = context.packageManager
    //获取所有已安装程序的包信息
    val packageInfos: List<PackageInfo> = packageManager.getInstalledPackages(0 or
      PackageManager.GET_ACTIVITIES or
          PackageManager.GET_SERVICES)
    //用于存储所有已安装程序的包名
    val packageNames = mutableListOf<String>()
    //从pinfo中将包名字逐一取出，压入pName list中
    for (i in packageInfos.indices) {
      val packName: String = packageInfos[i].packageName
      Log.e("zzm debug","packName : $packName")
      packageNames.add(packName)
    }
    //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
    return packageNames.contains(packageName)
  }
}